package com.taoye.thread;

import cn.hutool.core.date.DateUtil;

public class Demo32 {
    public static void main(String[] args) throws InterruptedException {
        Demo32Service service = new Demo32Service();
        Thread t = new Demo32ThreadA(service);
        t.setName("A");
        t.start();
        Thread t1 = new Demo32ThreadB(service);
        t1.setName("B");
        t1.start();
    }
}

class Demo32Service {

    /**
     * 这里使用字符串作为参数，用于使用锁
     */
    public void fun(String lock) {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + "线程执行了fun1，当前时间：" + DateUtil.now());
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + "线程fun1执行结束，当前时间：" + DateUtil.now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Demo32ThreadA extends Thread {
    Demo32Service service;

    public Demo32ThreadA(Demo32Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        // 这里调用的不是静态方法
        service.fun("LOCK-A");
    }
}

class Demo32ThreadB extends Thread {

    Demo32Service service;

    public Demo32ThreadB(Demo32Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.fun("LOCK-A");
    }
}
